﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace Kimd.Motion
{
    public class ControlCard
    {
        public string Description { get; set; }
        public short CardNo { get; set; }
        public string CardType { get; set; }
        public string ConfigFilePath { get; set; } = "";
        [XmlIgnore]
        public bool IsOpen { get; set; }
        [XmlIgnore]
        public ICard CardOperator { get; set; }
        [XmlIgnore]
        public IAxis AxisOperator { get; set; }
        [XmlIgnore]
        public ICoordinate CoordinateOperator { get; set; }
        [XmlIgnore]
        public IDigitalIO DigitalOperator { get; set; }
        [XmlIgnore]
        public IPdo PdoOperator { get; set; }
        private bool _isErr;
        [XmlIgnore]
        public bool IsErr
        {
            get 
            {
                _isErr = false;
                if (CardOperator != null && CardOperator.IsError)
                {
                    _lastError = CardOperator.LastError;
                    _isErr = true;
                }
                if (AxisOperator != null && AxisOperator.IsError)
                {
                    _lastError = AxisOperator.LastError;
                    _isErr = true;
                }
                if (CoordinateOperator != null && CoordinateOperator.IsError)
                {
                    _lastError = CoordinateOperator.LastError;
                    _isErr = true;
                }
                if (DigitalOperator != null && DigitalOperator.IsError)
                {
                    _lastError = DigitalOperator.LastError;
                    _isErr = true;
                }
                if(PdoOperator != null && PdoOperator.IsError)
                {
                    _lastError = PdoOperator.LastError;
                    _isErr = true;
                }
                return _isErr; 
            }
        }
        private string _lastError;
        [XmlIgnore]
        public string LastErrorMessage
        {
            get { return _lastError; }
        }

        public ControlCard()
        {

        }
        public ControlCard(short cardNo, string cardType, string description, string configFilePath)
            : this()
        {
            this.CardNo = cardNo;
            this.CardType = cardType;
            this.Description = description;
            this.ConfigFilePath = configFilePath;
        }
        public bool IsErrr { get { return CardOperator.IsError; } }
        public void Open()
        {
            IsOpen = CardOperator.Open(CardNo, ConfigFilePath);
        }

        public void Close()
        {
            CardOperator.Close();
            IsOpen = false;
        }

        public void Reset()
        {
            CardOperator.Reset();
        }
    }
}
